/**
 * 故障模块
*/

#include "fault.h"
#include "evtqueue.h"

Node faultlist;
uint8_t faultsbuf[sizeof(Node)*32];

void test_dofault()
{
    //测试fault模块
    EVT_T emp1 = {
        .eEvtKind = EVT_KIND_OP,
        .stOpEvt = OP_REV3_DOWN,
        .time = 13990
    };
    EVT_T emp2 = {
        .eEvtKind = EVT_KIND_OP,
        .stFaultEvt  = FAULT_BALLVAL_ABNORM,
        .time = 14000
    };
    EVT_T emp3 = {
        .eEvtKind = EVT_KIND_OP,
        .stFaultEvt = FAULT_24V_H,
        .time = 14500
    };
    EVT_T emp4 = {
        .eEvtKind = EVT_KIND_OP,
        .stExthEvt = EXTH_PUMP_OPEN_EVT,
        .time = 15000
    };
   
    fault_init_withbuf(&faultlist, faultsbuf, sizeof(faultsbuf));

    
    fault_write(&faultlist, emp1);
    fault_write(&faultlist, emp2);
    fault_write(&faultlist, emp3);
    fault_write(&faultlist, emp4);

//    realTimeFaultWrtie(emp1);
//    realTimeFaultWrtie(emp2);
//    realTimeFaultWrtie(emp3);
//    realTimeFaultWrtie(emp4);
  
    
    EVT_T emp5 = fault_read(&faultlist,2);
    
    
    DEBUG_LOG_INFO(DEBUG_LEVEL_2, "\nget time from list is %d\n",emp5.time);
}



/**
 * 故障时间处理函数
 * faultEvent: 故障事件
 * 故障事件处理函数，三个动作，将故障保存历史记录、
 * 将故障更新到实时故障列表，通知屏幕实时故障信息更新
 * 需要对传入参数的类型进行判断，确定是故障事件，且传入参数合法
*/
void faultHandle (EVT_T   faultEvent){
   


    // 1. 将故障保存到历史记录
    printf("故障已保存到历史记录.\n");

    // 2. 将故障更新到实时故障列表
    printf("故障已更新到实时故障列表.\n");

    // 3. 通知屏幕实时故障信息更新
    printf("实时故障信息已更新.\n");
}

/**
 * 故障链表初始化
 * faultEvent：需要插入节点的故障信息
 * 将故障事件数据插入实时故障链表
*/
void fault_init_withbuf(Node *faults, void *buf, int buflen) {
    INIT_LIST_HEAD(&faults->flist);
    nodebuf_init(&faults->faultbuf, buf, buflen, sizeof(struct task_t));

}

/**
 * 实时故障插入
 * faultEvent：需要插入节点的故障信息
 * 将故障事件数据插入实时故障链表
*/
void fault_write(Node *faults, EVT_T  faultEvent)
{

    Node* newFaultEvent = (Node*) nodebuf_malloc(&faults->faultbuf,0); // nodebuf.c 为新的故障节点分配内存

    newFaultEvent->data = faultEvent;
    list_add_tail(&newFaultEvent->flist, &faults->flist);
    
    
    //DEBUG_LOG_INFO(DEBUG_LEVEL_2, "---++++++++++COME %d HERE+++++++++---\n",faultEvent.time);
    //DEBUG_LOG_INFO(DEBUG_LEVEL_2, "---++++++++++COME %d HERE+++++++++---\n",newFaultEvent->data.time);
    
}

/**
 * 实时读取故障
 * numberL: 请求读取节点上第number个节点的数据
 * 返回 第number个节点的数据
 * 读取实时链表的第number的数据
*/
EVT_T fault_read(Node *faults, UINT8 num) {
    
    UINT16 COUNT = 0;
    struct list_head *fault_ptr, *safe_ptr;
    list_for_each_safe(fault_ptr, safe_ptr, &faults->flist) {
        Node *newfault = list_entry(fault_ptr,Node,flist);
        COUNT++;
        
//        DEBUG_LOG_INFO(DEBUG_LEVEL_2, "---++++++++++????? %d ?????+++++++++---\n",newfault->data.time);
//        DEBUG_LOG_INFO(DEBUG_LEVEL_2, "---++++++++++?????count =  %d ?????+++++++++---\n",COUNT);
//        DEBUG_LOG_INFO(DEBUG_LEVEL_2, "---++++++++++?????num =  %d ?????+++++++++---\n",num);

        if(COUNT == num){

            return newfault->data;
        }
    }
}
